var rewire = require("rewire")
const { filterAsync } = rewire('./common/combinator.cjs')
const { elemFindItem, elemClick, elemGetHtml, elemGetItem, elemLocation, elemGetList, elemFindList, elemGetValue, elemGetText, elemInput, elemInputSet, elemWaitUtil, elemExists } = rewire('./common/webdriver.cjs')
const { updateUserInfo, setFollowState } = rewire('./drainage/db.cjs')
const { ramdomRange, extractNum, shortCNToTimestamp } = rewire('./common/utils.cjs')
const { readFile } = rewire('./common/file.cjs')
const { waitTime } = rewire('./common/appium.cjs')
const { getRandomGreeting } = rewire('./state.cjs')

// 自动发文
async function autoPost(client) {
    console.log("点击发布")
    const el = await client.$('[resource-id="com.instagram.android:id/creation_tab"]')
    await el.click()

    console.log("选目录")
    const pickuBtn = await client.$('[resource-id="com.instagram.android:id/spinner_title_text"]')
    await pickuBtn.waitForExist({ timeout: 5000 })
    await pickuBtn.click()
    const mumuPicBtn = await client.$('[resource-id="com.instagram.android:id/format_picker_pager"]')
    await mumuPicBtn.waitForExist({ timeout: 5000 })
    await mumuPicBtn.click()

    console.log("点击多选")
    const multi = await client.$('[resource-id="com.instagram.android:id/multi_select_slide_button_alt"]')
    await multi.waitForExist({ timeout: 5000 })
    await multi.click()

    console.log("选择对应图片")
    const pics1 = await client.$('[resource-id="com.instagram.android:id/media_picker_grid_view"]').$$('[class-name="android.widget.CheckBox"]')[1]
    await pics1.waitForExist({ timeout: 5000 })
    await pics1.click()

    console.log("点击下一步")
    const next1 = await client.$('[resource-id="com.instagram.android:id/next_button_imageview"]')
    await next1.click()

    console.log("点击下一步")
    const picBox = await client.$('[resource-id="com.instagram.android:id/filter_view_container"]')
    await picBox.waitForExist({ timeout: 5000 })
    await next1.click()

    console.log("点击下一步")
    const box1 = await client.$('[resource-id="com.instagram.android:id/album_indicator"]')
    await box1.waitForExist({ timeout: 5000 })
    await next1.click()
}

async function followBigVTask(client, uid) {
    await enterUserInfoPage(client, uid)
    const info = await getUserInfo(client)
    await updateUserInfo(info)
    await enterFirstTopic(client)
    await followTopicFansAndComment(client)
}

async function getUserInfo(client) {
    console.log("获取用户信息")
    const uidEl = await elemFindItem(client, '[resource-id="com.instagram.android:id/action_bar_title"]')
    const postEl = await elemFindItem(client, '[resource-id="com.instagram.android:id/row_profile_header_textview_post_count"]')
    const fanEl = await elemFindItem(client, '[resource-id="com.instagram.android:id/row_profile_header_textview_followers_count"]')
    const followEl = await elemFindItem(client, '[resource-id="com.instagram.android:id/row_profile_header_textview_following_count"]')
    
    const nameEl = await elemGetItem(client, '[resource-id="com.instagram.android:id/profile_header_full_name"]')
    
    const bioEl = await elemGetItem(client, '[resource-id="com.instagram.android:id/profile_header_bio_text"]')
    const websiteEl = await elemGetItem(client, '[resource-id="com.instagram.android:id/profile_header_website"]')
    const busEl = await elemGetItem(client, '[resource-id="com.instagram.android:id/profile_header_business_category"]')

    
    const data = {
        uid: await elemGetText(uidEl),
        posts: extractNum(await elemGetText(postEl)),
        fans: extractNum(await elemGetText(fanEl)),
        follows: extractNum(await elemGetText(followEl)),
        intro: (await bioEl.isExisting()) ? (await elemGetText(bioEl)) : '',
        other: JSON.stringify({
            name: (await nameEl.isExisting()) ? (await elemGetText(nameEl)) : '',
            website: (await websiteEl.isExisting()) ? (await elemGetText(websiteEl)) : '',
            business: (await busEl.isExisting()) ? (await elemGetText(busEl)) : '',
        })
    }
    return data
}

// 进入指定ID的用户界面
async function enterUserInfoPage(client, uid) {
    console.log("进入大V主界面：" + uid)
    const el = await elemFindItem(client, '[resource-id="com.instagram.android:id/profile_tab"]')
    await elemClick(el)
    
    const el2 = await elemFindItem(client, '[resource-id="com.instagram.android:id/row_profile_header_following_container"]')
    await elemClick(el2)

    const el3 = await elemFindItem(client, '[resource-id="com.instagram.android:id/row_search_edit_text"]')
    await elemInput(el3, uid)

    const el4 = await elemFindItem(client, '[resource-id="com.instagram.android:id/follow_list_container"]')
    await elemClick(el4)
}


// 点击第一个图
async function enterFirstTopic(client) {
    console.log("点击第一个图")
    const el1 = await client.$('[resource-id="com.instagram.android:id/profile_viewpager"]')
    const el2 =  await el1.$$('[resource-id="com.instagram.android:id/media_set_row_content_identifier"]')[0].$$('[class-name="android.widget.Button"]')[0]
    await el2.waitForExist({ timeout: 5000 })
    await el2.click()
}

// 关注某个主题的粉丝
async function followTopicFansAndComment(client) {
    console.log("关注某个主题的粉丝")
    const eRs = await enterCommentPage(client)
    if (!eRs) {
        return
    }
    let elemList = await findCommentList(client)

    console.log("开始筛选")
    elemList = await filterAsync(elemList, async (elem) => {
        return !((await isEmptyComment(elem)) || (await isOwnerComment(elem)))
    })

    const len = elemList.length
    console.log("开始遍历")
    for (let i = 0; i < len; i++) {
        console.log("逐个遍历: " + i)
        const elem = elemList[i]
        await elemClick(await nameBox(elem))
        const info = await getUserInfo(client)
        await updateUserInfo(info)
        if (! ((await isFollow(client))
               || (await isPrivate(client))
               || (await emptyTopic(client)))) {
            await clickFollowBtn(client)
            await waitTime(client, 500)
            await testMove(client)
            await setFollowState(info['uid'], true)
            await testMove(client)
            await commentFirstTopic(client)
        }
        await backPage(client)
    }
    
    await backPage(client)
}

// 点击回退按钮
async function backPage(client) {
    const el = await elemFindItem(client, '[resource-id="com.instagram.android:id/action_bar_button_back"]')
    await elemClick(el)
}

async function backPage2(client) {
    await client.back()
    await waitTime(client, 500)
}

// 进入评论区
async function enterCommentPage(client) {
    console.log("进入评论区")
    const el3 = await elemGetItem(client, '[resource-id="com.instagram.android:id/row_feed_button_comment"]')
    if (await el3.isExisting()) {
        await elemClick(el3)
        return true
    }
    return false
}

// 获取评论列表
async function findCommentList(client) {
    console.log('获取评论列表')
    const el = await elemFindItem(client, '[resource-id="com.instagram.android:id/layout_listview_parent_container"]')
    const elList = await el.$$('[resource-id="com.instagram.android:id/row_comment"]')
    return elList
}


async function isEmptyComment(item) {
    const el = await item.$('[resource-id="com.instagram.android:id/row_comment_textview_comment"]')
    if (await isExists(el)) {
        const text = await el.getText()
        const arr = text.split(" ")
        return arr.length < 2
    }
    return true
}

async function isOwnerComment(item) {
    const el = await item.$('[resource-id="com.instagram.android:id/row_comment_imageview"]')
    return !(await el.isExisting())
}

async function nameBox(item) {
    const el = await item.$('[resource-id="com.instagram.android:id/row_comment_textview_comment"]')
    return await el.$('[class-name="android.widget.Button"]')
}


// 是否已关注
async function isFollow(client) {
    const el = await elemFindItem(client, '[resource-id="com.instagram.android:id/profile_header_actions_top_row"]')
    const p = await el.$$('[class-name="android.widget.Button"]')[0]
    const text = await elemGetText(p)
    return text !== '关注'
}

// 是否是不开放
async function isPrivate(client) {
    return await elemExists(client, '[resource-id="com.instagram.android:id/row_profile_header_empty_profile_notice_title"]')
}

async function emptyTopic(client) {
    const b = await elemExists(client, '[resource-id="com.instagram.android:id/profile_viewpager"]')
    return !b
}

async function clickFollowBtn(client) {
    const p = await client.$('[resource-id="com.instagram.android:id/profile_header_actions_top_row"]').$$('[class-name="android.widget.Button"]')[0]
    await elemClick(p)
}

// 评论第一个主题
async function commentFirstTopic(client) {
    await enterFirstTopic(client)
    await waitTime(client, 800)
    await testMove(client)
    const count = await getTopicCommentCount(client)
    if (count > 100) {
        await backPage2(client)
        return
    }
    const rs = await enterCommentPage(client)
    if (rs) {
        const text = await getRandomGreeting()
        await commentTopic(client, text)
    }
    
    await backPage(client)
}

async function commentFirstTopic2(client) {
    await enterFirstTopic(client)
    await waitTime(client, 800)
    await testMove(client)
    const count = await getTopicCommentCount(client)
    if (count > 100) {
        await backPage2(client)
        return
    }
    const postTime = await getTopicTime(client)
    if ((currentMs() - postTime) > (3600 * 24 * 1000)) {
        await backPage2(client)
        return
    }
    
    const rs = await enterCommentPage(client)
    if (rs) {
        if (await isReadyComment(client)) {
            await backPage2(client)
            return
        }
        const text = await getRandomGreeting()
        await commentTopic(client, text)
    }
    
    await backPage(client)
}

async function isReadyComment(client) {
    const commentList = await findCommentList(client)
    const rs = await filterAsync(commentList, async (item) => {
        const name = await getCommentUserName(item)
        return (name == 'sylvainluz')
    })
    return rs.length > 0
}


async function getCommentUserName(item) {
    const el = await item.$('[resource-id="com.instagram.android:id/row_comment_textview_comment"]')
    if (await isExists(el)) {
        const text = await el.getText()
        const arr = text.split(" ")
        return arr[0]
    }
    return '未命名'
}

async function getTopicTime(client) {
    const el = await elemFindItem(client, '')
    const text = await elemGetText(el)
    const time = shortCNToTimestamp(text)
    return time
}

// 获取评论总数
async function getTopicCommentCount(client) {
    const el = await elemGetItem(client, '[resource-id="com.instagram.android:id/row_feed_view_all_comments_text"]')
    if (await el.isExisting()) {
        const text = await elemGetText(el)
        const count = extractNum(text)
        return count
    }
    return 0
}


// 评论当前主题
async function commentTopic(client, text) {
    const el = await elemFindItem(client, '[resource-id="com.instagram.android:id/layout_comment_thread_edittext"]')
    if (await el.isEnabled()) {
        await elemInput(el, text)
    }
    const postBtn = await elemFindItem(client, '[resource-id="com.instagram.android:id/layout_comment_thread_post_button"]')
    if (postBtn.isExisting()) {
        await elemClick(postBtn)
        await waitTime(client, 1000)
    }
    await backPage(client)
}

async function testMove(client) {
    await client.touchPerform([
        { action: 'press', options: { x: 30, y: 800 }},
        { action: 'wait', options: { ms: 800 }},
        { action: 'moveTo', options: { x: 135, y: 459 }},
        { action: 'release' }
    ])
}



async function isExists(el) {
    return await el.isExisting()
}


module.exports = {autoPost, followBigVTask, getUserInfo, enterUserInfoPage, enterFirstTopic, followTopicFansAndComment, backPage, backPage2, enterCommentPage, findCommentList, isEmptyComment, isOwnerComment, nameBox}
